import socket

# 设备信息
ip_address = '192.168.10.11'
port = 5020

register_address1 = 0x0003  # 适当设置要写入的寄存器地址

# 要写入的值（数字1）
value_to_write = 0x0001

# Modbus TCP 请求帧 - 写入寄存器
transaction_id = 0x1234
unit_id = 0x01
write_function_code = 0x05


def build_write_request_frame(register_address1, value):
    return bytearray([
        transaction_id >> 8, transaction_id & 0xFF,
        0x00, 0x00,  # Protocol Identifier
        0x00, 0x06,  # Length
        unit_id,
        write_function_code,
        register_address1 >> 8, register_address1 & 0xFF,
        value >> 8, value & 0xFF  # Write value
    ])


# 创建 Socket 连接
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((ip_address, port))

try:
    # 写入寄存器
    write_request_frame = build_write_request_frame(register_address1, value_to_write)
    client_socket.send(write_request_frame)


except KeyboardInterrupt:
    # 当用户按下Ctrl+C时，关闭连接
    pass
# 关闭连接
client_socket.close()
